package com.baitengsoft.patentapimonitor.api.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.baitengsoft.patentapimonitor.api.dao.ScheduleJobDao;
import com.baitengsoft.patentapimonitor.api.entity.AdminDataauditEntity;
import com.baitengsoft.patentapimonitor.api.entity.CfgDictionaryEntity;
import com.baitengsoft.patentapimonitor.api.entity.ScheduleJobEntity;
import com.baitengsoft.patentapimonitor.api.entity.WebPlatformEntity;
import com.baitengsoft.patentapimonitor.api.model.AdminDataauditViewModel;
import com.baitengsoft.patentapimonitor.api.model.param.AdminDataauditParam;
import com.baitengsoft.patentapimonitor.api.model.param.EditAdminDataauditParam;
import com.baitengsoft.patentapimonitor.api.service.AdminDataauditService;
import com.baitengsoft.patentapimonitor.api.service.CfgDictionaryService;
import com.baitengsoft.patentapimonitor.api.service.ScheduleJobService;
import com.baitengsoft.patentapimonitor.api.service.WebPlatformService;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.SysParamaterUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Admin on 2018/1/5.
 */
@Service
public class AdminDataauditServiceImpl extends BaseServiceImpl<AdminDataauditEntity> implements AdminDataauditService {

    @Autowired
    org.dozer.Mapper mapper;
    @Autowired
    private WebPlatformService webPlatformService;
    @Autowired
    private CfgDictionaryService cfgDictionaryService;
    @Autowired
    private ScheduleJobService scheduleJobService;
    @Autowired
    private ScheduleJobDao scheduleJobDao;

    @Autowired
    private SysParamaterUtil sysParamaterUtil;

    @Override
    public PageResult<AdminDataauditViewModel> searchDataaudit(AdminDataauditParam param) {

        PageHelper.startPage(param.getPage(), param.getPageSize());
        Mapper<AdminDataauditEntity> mapperTk = getMapper();
        Example example = new Example(AdminDataauditEntity.class);
        example.setOrderByClause("createdate DESC");
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", -1);
        if (param.getPlatformid() != null && param.getPlatformid() > 0) {
            criteria.andEqualTo("platformid", param.getPlatformid());
        }
        if (StringUtils.isNotBlank(param.getDateStartStr())) {
            criteria.andGreaterThanOrEqualTo("createdate", dateConversion(param.getDateStartStr()));
        }
        if (StringUtils.isNotBlank(param.getDateEndStr())) {
            criteria.andLessThanOrEqualTo("createdate", dateConversion(param.getDateEndStr()));
        }
        if (param.getAudittype() != null && param.getAudittype() > 0) {
            criteria.andEqualTo("audittype", param.getAudittype());
        }
        List<AdminDataauditEntity> entities = mapperTk.selectByExample(example);
        PageInfo<AdminDataauditEntity> pageInfo = new PageInfo<>(entities);
        if (entities != null && entities.size() > 0) {
            List<AdminDataauditViewModel> viewModels = new ArrayList<>();
            for (AdminDataauditEntity entity : entities) {
                AdminDataauditViewModel viewModel = new AdminDataauditViewModel();
                mapper.map(entity, viewModel);
                if (entity.getPlatformid() != null && entity.getPlatformid() > 0) {
                    WebPlatformEntity webPlatformEntity = webPlatformService.searchById(entity.getPlatformid());
                    if (webPlatformEntity != null) {
                        viewModel.setPlatform(webPlatformEntity.getName());
                    }

                }
                if (entity.getAudittype() != null && entity.getAudittype() > 0) {
                    List<CfgDictionaryEntity> cfgDictionaryEntities = cfgDictionaryService.searchDictionaryByCode("1002");
                    List<CfgDictionaryEntity> newCfgDictionaryEntities = cfgDictionaryEntities.stream().filter(x -> x.getValues().equals(String.valueOf(entity.getAudittype()))).collect(Collectors.toList());
                    viewModel.setAudittypeStr(newCfgDictionaryEntities.get(0).getName());
                }
                viewModels.add(viewModel);
            }
            return new PageResult<AdminDataauditViewModel>(viewModels, param.getPage(), param.getPageSize(), (int) pageInfo.getTotal());
        }
        return null;
    }

    @Override
    public AdminDataauditViewModel searchById(int id) {

        if (id > 0) {
            AdminDataauditEntity entity = queryById(id);
            if (entity != null) {
                AdminDataauditViewModel viewModel = new AdminDataauditViewModel();
                mapper.map(entity, viewModel);
                if (entity.getPlatformid() != null && entity.getPlatformid() > 0) {
                    WebPlatformEntity webPlatformEntity = webPlatformService.searchById(entity.getPlatformid());
                    if (webPlatformEntity != null) {
                        viewModel.setPlatform(webPlatformEntity.getName());
                    }
                }
                if (entity.getAudittype() != null && entity.getAudittype() > 0) {
                    List<CfgDictionaryEntity> cfgDictionaryEntities = cfgDictionaryService.searchDictionaryByCode("1002");
                    List<CfgDictionaryEntity> newCfgDictionaryEntities = cfgDictionaryEntities.stream().filter(x -> x.getValues().equals(String.valueOf(entity.getAudittype()))).collect(Collectors.toList());
                    viewModel.setAudittypeStr(newCfgDictionaryEntities.get(0).getName());
                }
                return viewModel;
            }
        }
        return null;
    }

    @Override
    @Transactional
    public Integer editDataaudit(EditAdminDataauditParam param, int userId) {
        Integer successId = 0;
        AdminDataauditEntity entity = new AdminDataauditEntity();
        mapper.map(param, entity);
        entity.setUpdatedate(new Date());
        entity.setUpdateoperid(userId);
        if (param.getId() != null && param.getId() > 0) {//编辑
            successId = updateByNotNull(entity);

            //同步更新schedule_job中的信息
            ScheduleJobEntity scheduleJobEntity = scheduleJobDao.selectByDataId(entity.getId());
            if (scheduleJobEntity == null) {
                throw new RuntimeException("没有对应的scheduleJobEntity");
            }

            Map<String, Object> paramsMap = new HashMap<>();

            paramsMap.put("id", scheduleJobEntity.getId());
            paramsMap.put("params", entity.getSearchstrategy());
            int updateEffectiveRows = scheduleJobDao.updateParamsById(paramsMap);
            if (updateEffectiveRows <1) {
                throw new RuntimeException("更新失败");
            }
            return successId;
        } else {//新增
            entity.setStatus(1);
            entity.setCreatedate(new Date());
            entity.setCreateoperid(userId);
            successId = saveByNotNull(entity);
            if (successId == 0) return 0;//新增失败
            //添加数据更新表
            //ResourceBundle res=ResourceBundle.getBundle("/ScheduleJob");
//            ResourceBundle res= TemplateFileUtil.getBundle("ScheduleJob");
//            String beanName=res.getString("beanName");
//            String methodName=res.getString("methodName");
            ScheduleJobEntity scheduleJobEntity = new ScheduleJobEntity();
            scheduleJobEntity.setDataid(entity.getId());
            scheduleJobEntity.setBeanname(sysParamaterUtil.getBeanName());
            scheduleJobEntity.setMethodname(sysParamaterUtil.getMethodName());
            scheduleJobEntity.setParams(entity.getSearchstrategy());
            scheduleJobEntity.setCronexpression("0 59 2 ? * FRI");
            scheduleJobEntity.setStatus(0);
            scheduleJobEntity.setCreatedate(new Date());
            Integer sjsId = scheduleJobService.saveScheduleJob(scheduleJobEntity);


            if (sjsId == 0) return 0;//新增数据更新表失败

        }

        //更新定时任务


        return successId;
    }

    @Override
    @Transactional
    public Integer delDataauditByIds(String idStr, int userId) {

        if (StringUtils.isNotBlank(idStr)) {
            String[] ids = idStr.split(",");
            AdminDataauditEntity entity = new AdminDataauditEntity();
            entity.setStatus(-1);
            entity.setUpdateoperid(userId);
            for (String id : ids) {
                entity.setId(Integer.parseInt(id));
                entity.setUpdatedate(new Date());
                Integer successId = updateByNotNull(entity);
                if (successId == 0) return 0;//删除失败

                //删除数据更新表
                int scheduleId = scheduleJobDao.delScheduleJobByDataId(Integer.parseInt(id));
                if (scheduleId == 0) return 0;//删除失败
                //删除定时任务
                HttpRequest.post(sysParamaterUtil.getDeleteQuartzJobUrl()).body(JSONUtil.toJsonStr(new  long[]{scheduleId})).execute();
            }
            return 1;//删除成功
        }
        return 0;//删除失败
    }

    @Override
    public Integer saveDataaudit(AdminDataauditEntity entity) {
        return saveByNotNull(entity);
    }


    public Date dateConversion(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
